<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <title>Document</title>
</head>
<body>
  <center>
    <p><a href="https://github.com/zhangshenhua/cosmos">cosmos</a></p>
    <div id="console0">
      <textarea id='text' name="Text1" cols="80" rows="5"></textarea>
      <button id='btn_send' type="button">发送</button></br>
      <button id='btn_pant_off' type="button">关闭心跳</button>
      <button id='btn_pant_on' type="button">开启心跳</button></br>
    </div>
  </center>
  <br>
  <div id="blocks"></div>
  
  <script>
    var ws = new WebSocket(`ws://${window.location.hostname}:2333${window.location.pathname}`);

    function uri_parse (str_uri) {
      var uri = str_uri;
      var cid, uid_from, uid_to;

      var group = uri.match('^/(.*?)(/([^/@]*))?(@([^/]*))?$');
      cid = '/' + group[1];
      uid_from = group[3];
      uid_to = group[5];
      
      console.log({"cid": decodeURI(cid), "uid_from": decodeURI(uid_from), "uid_to": decodeURI(uid_to)});
      return {"cid": decodeURI(cid), "uid_from": decodeURI(uid_from), "uid_to": decodeURI(uid_to)}
    }

    var uri_hash = uri_parse(window.location.pathname),
        cid = uri_hash.cid,
        uid_from = uri_hash.uid_from,
        uid_to = uri_hash.uid_to;


    function makeMessage(from, to, text) {
      return JSON.stringify(
          {
              'from': from,
              'to': to,
              'text': text,
          }
      );
    }


    timerPant = undefined;

    function pantOn (ms=30000) {
      timerPant && pantOff();
      timerPant = setInterval(
        () => {
          ws.send(makeMessage(
            uid_from, '', '我在'));
        },
        ms
      );
    }

    function pantOff () {
      clearInterval(timerPant);
    }
    

    $('#btn_pant_off').on('click',
      ()=>{
        pantOff();
      }
    );

    $('#btn_pant_on').on('click',
      ()=>{
        pantOn();
      }
    );

    ws.onopen = function () {
      //pantOn();

      document.getElementById('btn_send').onclick = () => {
        ws.send(
          makeMessage(
            uid_from,
            uid_to,
            $('#text').val()));
        $('#text').val('');
      };
    };

    ws.onmessage = (e) => {
      var str = e.data;
      var json_data = JSON.parse(str);
      var jscodes = json_data.text.match(/<js>([\s\S]*?)<\/js>/m);
      
      
      let $block = $('<div class="block"></div>');
        $('<div class="dateAdded"></div>')
          .text(     
            json_data.dateAdded ? (new Date(json_data.dateAdded)).toLocaleString() :
                                  (new Date()).toLocaleString())
          .appendTo($block);

        $('<div class="head"></div>')
          .text(json_data.from + 
              (json_data.to ? `@${json_data.to}`: '') + ':' )
          .appendTo($block);

        let $p = $('<div class="content"></div>');
          if (jscodes) {
            eval(jscodes[1]);
          } else {
            $p.html(json_data.text);
          }
          $p.appendTo($block);
        $('<pre></pre>').text(json_data.text).appendTo($block);
        $('<hr>').appendTo($block);
        $block.prependTo($("#blocks"));
    };
  </script>
</body>
</html>
